package com.ywk.rabbitmqProd.base.sender;

import com.google.gson.Gson;
import com.ywk.rabbitmqProd.base.config.MQConfig;
import com.ywk.rabbitmqProd.business.message.BusinessMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author zbh
 * @Date 2023/5/18
 */
@Component
@Slf4j
public class MQSender {
    @Autowired
    AmqpTemplate amqpTemplate;

    public void send(Object message) {
        log.info("send message："+message);
        amqpTemplate.convertAndSend(MQConfig.QUEUE,message);
    }

    public void sendDirect(Object message) {
        String msg=message.toString();
        log.info("send direct message:"+msg);
        amqpTemplate.convertAndSend(MQConfig.DIRECT_EXCHANGE,MQConfig.DIRECT_ROUTING_KEY1, msg+"1");
        amqpTemplate.convertAndSend(MQConfig.DIRECT_EXCHANGE,MQConfig.DIRECT_ROUTING_KEY2, msg+"2");
    }

    public void sendFanout(Object message) {
        String msg=message.toString();
        log.info("send fanout message:"+msg);
        amqpTemplate.convertAndSend(MQConfig.FANOUT_EXCHANGE, msg);
    }

    public void sendTopic(Object message){
        String msg=message.toString();
        log.info("topicSend message："+msg);
        amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE,"topic.key1",message+"1");
        amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE,"topic.key2",message+"2");
    }

    public void sendHeader(Object message) {
        String msg=message.toString();
        log.info("send fanout message:"+msg);
        MessageProperties properties = new MessageProperties();
        properties.setHeader("header1", "value1");
        properties.setHeader("header2", "value2");
        Message obj = new Message(msg.getBytes(), properties);
        amqpTemplate.convertAndSend(MQConfig.HEADERS_EXCHANGE, "", obj);
    }

    public void sendBusinessMessage(BusinessMessage message){
        Gson gson = new Gson();
        String json = gson.toJson(message);
        log.info("sendBusinessMessage() message:"+json);
        amqpTemplate.convertAndSend(MQConfig.BUSINESS_QUEUE,json);
    }

}
